﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jacaranda.Model
{
    public class SortCriteria
    {
        public SortCriteria()
        {
            Fields = new List<SortFieldCriteria>();
        }

        public List<SortFieldCriteria> Fields { get; private set; }


        internal Type EntityType { get; set; }

        public string GenerateSql()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" ORDER BY ");
            Fields.ForEach(i=> sb.Append(Metadata.Type(EntityType).Fields.First(j => j.PropertyName == i.Property.Name).FieldName)
                .Append((i.Order == SortOrder.Ascending) ? " ASC":" DESC").Append(","));
            string sql = sb.ToString();
            return sql.EndsWith(",")? sql.Substring(0,sql.Length - 1):sql;
        }

        public SortCriteria OrderBy(string propertyName)
        {
            Fields.Add(new SortFieldCriteria() { Property = new AbstractProperty(propertyName), Order = SortOrder.Ascending });
            return this;
        }

        public SortCriteria OrderByDesc(string propertyName)
        {
            Fields.Add(new SortFieldCriteria() { Property = new AbstractProperty(propertyName), Order = SortOrder.Descending });
            return this;
        }
    }
}
